package com.tongcao.cn.contoller;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.model.BucketInfo;
import com.aliyun.oss.model.ObjectListing;
import com.tongcao.cn.dfire.result.ResultMap;
import com.tongcao.cn.dfire.utils.ApiResultUtil;
import com.tongcao.cn.service.IOssService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * @Author:tongcao
 * @Date:2018/9/11 11:21
 * Description:
 */
@Api("文件上传与下载")
@Controller
@Slf4j
public class FileController {

    @Resource
    private IOssService ossService;


    @GetMapping("uploadTest")
    private ResultMap ossTest() {
        BucketInfo info = ossService.getBucketInfo("bookeross");
        ObjectListing bookeross = ossService.listFile("bookeross");
        return null;
    }

    @PostMapping(value = "/upload")
    @ResponseBody
    public ResultMap upload(@RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            return ApiResultUtil.failResult("上传失败");
        }

        try {
            String originalFilename = file.getOriginalFilename();
            log.info("上传的文件名为：" + originalFilename);

            String suffiName = originalFilename.substring(originalFilename.lastIndexOf("."));
            log.info("文件后缀名为：" + suffiName);
            // 设置文件存储路径
            String filePath = "D:/upload/";
            String path = filePath + originalFilename;
            File dest = new File(path);

            String img2Oss = ossService.uploadImg2Oss(file);
            log.info(JSON.toJSONString(img2Oss));
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                // 新建文件夹
                dest.getParentFile().mkdirs();
            }
            // 文件写入
            file.transferTo(dest);
            return ApiResultUtil.successResult("upload success");
        } catch (IOException e) {
            log.info(e.getMessage());

        }
        return ApiResultUtil.failResult("upload fail");
    }


    @PostMapping("/batch")
    public ResultMap handleFileUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            String filePath = "D:/upload/";
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    //设置文件路径及名字
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File(filePath + file.getOriginalFilename())));
                    stream.write(bytes);// 写入
                    stream.close();
                } catch (Exception e) {
                    stream = null;
                    return ApiResultUtil.failResult("第 " + i
                            + " 个文件上传失败因为文件为空" + e.getMessage());
                }
            } else {
                return ApiResultUtil.failResult("第 " + i
                        + " 个文件上传失败因为文件为空");

            }
        }
        return ApiResultUtil.successResult("upload batch file success!");
    }

}
